import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
//https://leetcode.cn/problems/binary-tree-preorder-traversal/submissions/555952717/
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        //当栈为空时，说明前序遍历已完成
        while (!stack.isEmpty() || cur != null) {
            //cur不为空就要进栈，并添加进顺序表
            //cur = cur.left
            while (cur != null) {
                stack.push(cur);
                list.add(cur.val);
                cur = cur.left;
            }
            //当cur为空时，弹出栈顶元素（top），赋给cur其右子树
            //若cur还是为空（top.right为空），循环过来继续弹出元素，并赋给cur新的top.right
            TreeNode top = stack.pop();
            cur = top.right;
        }
        return list;
    }
}
